package com.cwits.wifi.ui.fragment;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseFragment;
import com.cwits.wifi.data.beans.FileInfo;
import com.cwits.wifi.ui.activity.MainActivity;
import com.cwits.wifi.ui.activity.VideoPlayerActivity;
import com.cwits.wifi.ui.dialog.OneDialog;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.ui.service.EncodeAVIToMP4Service;
import com.cwits.wifi.ui.view.TasksCompletedView;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.BitmapCache;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.ThreadPoolManager;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class VideoFragment extends BaseFragment implements View.OnClickListener {
    private ProgressDialog pd;
    private View mView;
    private ListView mListView;
    private RelativeLayout mRlRight, mRlBottom;
    private LinearLayout mLlNoVideo;
    private ImageView mImRight;
    private FileAdapter mAdapter;
    private MainApplication mApplication;
    private String defaultPath;
    private List<FileInfo> allDataInfoList = null;
    private List dataInfoList = null;
    private BitmapCache mBitmapCache;
    private List mSelectList;
    private boolean isSelect = false;
    HashMap<Integer, Boolean> state;
    private MainActivity mainAct;
    private CheckBox mCbSelectAll;
    private TwoDialog twoDialog;
    private SyncResourceLoader syncResourceLoader = new SyncResourceLoader();
    private int start = -1, end = -1;
    private boolean mIsTouchUpdate = false;
    private OneDialog oneDialog;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ENCORDING_CURRENT_START)) {
                //do nothing
                String currentStarPath = intent.getStringExtra(ACTION_ENCORDING_CURRENT_START);
                if (allDataInfoList != null && allDataInfoList.size() != 0) {
                    for (int i = 0; i < allDataInfoList.size(); i++) {
                        if (currentStarPath.equals(allDataInfoList.get(i).getPath())) {
                            allDataInfoList.get(i).setTranscod(2);
                            mAdapter.updataView(i, mListView);
                        }
                    }
                }

            } else if (action.equals(ACTION_ENCORDING_CURRENT_END)) {
                String currentEndPath = intent.getStringExtra(ACTION_ENCORDING_CURRENT_END);
                if (allDataInfoList != null && allDataInfoList.size() != 0) {
                    for (int i = 0; i < allDataInfoList.size(); i++) {
                        if (currentEndPath.equals(allDataInfoList.get(i).getPath())) {
                            allDataInfoList.get(i).setTranscod(1);
                            mAdapter.updataView(i, mListView);
                        }
                    }
                }
            }
        }
    };


    public VideoFragment() {
        // Required empty public constructor
    }

    /**
     * 取消选择
     */
    private void closeSelect() {
        mRlBottom.setVisibility(View.GONE);
        mainAct.selectAllT();
        mCbSelectAll.setChecked(false);
        isSelect = false;
    }

    /**
     * 进入选择
     */
    private void openSelect() {
        mRlBottom.setVisibility(View.VISIBLE);
        mainAct.selectAllF();
        isSelect = true;
    }

    public void selectAll() {

        if (isSelect) {
            //取消选择模式
            closeSelect();
            mAdapter.notifyDataSetChanged();
        } else {
            //进入选择模式
            openSelect();
            state.clear();
            mSelectList.clear();
            mAdapter.notifyDataSetChanged();

        }
        //showToastLong("这是VideoFragment");
    }

    public void initSelectAllCheckBox() {
        mCbSelectAll.setChecked(false);
    }

    public boolean getIsSelect() {
        return isSelect;
    }

    @Override
    protected void onVisible() {
        super.onVisible();

    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (getActivity() != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
        isSelect = false;
        if (mSelectList != null)
            mSelectList.clear();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_video, container, false);

        init();
        return mView;
    }

    private void initReceive() {
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_ENCORDING_CURRENT_START);
        intentFilter.addAction(IAction.ACTION_ENCORDING_CURRENT_END);
        getActivity().registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onResume() {
        super.onResume();
        initReceive();
        initData();
        if (mBitmapCache == null) {
            mBitmapCache = BitmapCache.getInstance();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBitmapCache != null) {
            mBitmapCache.clearCache();
            mBitmapCache = null;
        }
    }

    private String getMP4Path(FileInfo fileInfo) {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + fileInfo.getTitle().substring(0, fileInfo.getTitle().lastIndexOf(".")) + ".mp4";
    }

    private void initData() {


        if (allDataInfoList != null) {
            allDataInfoList.clear();
        }
        allDataInfoList = AppUtil.getLocalFileInfo(defaultPath);

        Iterator<FileInfo> stuIter = allDataInfoList.iterator();
        while (stuIter.hasNext()) {
            FileInfo student = stuIter.next();
            if (student.getTitle().substring(18, 22).equals(".JPG") || student.getTitle().length() != 22) {
                stuIter.remove();
            } else {
                if (isExist(getMP4Path(student))) {
                    student.setTranscod(1);
                } else {
                    if (EncodeAVIToMP4Service.getIsEncoding() && student.getPath().equals(EncodeAVIToMP4Service.getCurrentEncodePath())) {
                        student.setTranscod(2);
                    } else {
                        student.setTranscod(3);
                    }
                }
            }

        }
        mAdapter.notifyDataSetChanged();

        if (allDataInfoList.size() == 0) {
            mLlNoVideo.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        }
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        syncResourceLoader.lock();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        mIsTouchUpdate = false;
                        loadImage();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        mIsTouchUpdate = true;
                        syncResourceLoader.lock();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

    }

    protected void loadImage() {

        syncResourceLoader.setLoadLimit(start, end);
        syncResourceLoader.unlock();
        start = -1;
        end = -1;

    }

    private void init() {
        mSelectList = new ArrayList();
        mainAct = (MainActivity) getActivity();
        state = new HashMap<Integer, Boolean>();
        mApplication = (MainApplication) this.getActivity().getApplication();
        defaultPath = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video";
        mRlBottom = (RelativeLayout) mView.findViewById(R.id.video_rl_bottom);
        mRlBottom.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mLlNoVideo = (LinearLayout) mView.findViewById(R.id.video_ll_no_video);
        mListView = (ListView) mView.findViewById(R.id.video_listview);
        mRlRight = (RelativeLayout) mView.findViewById(R.id.video_rl_right);
        mImRight = (ImageView) mView.findViewById(R.id.video_im_right);
        mCbSelectAll = (CheckBox) mView.findViewById(R.id.video_cb_select);
        //mVideoMap = new HashMap<String, List<FileInfo>>();
        dataInfoList = new ArrayList();
        mAdapter = new FileAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox cb = (CheckBox) view.findViewById(R.id.item_video_cb);
                if (allDataInfoList.get(position).getTranscod() == 2 || allDataInfoList.get(position).getTranscod() == 3) {
                    cb.setVisibility(View.GONE);
                    if (!isSelect) {
                        if (allDataInfoList.get(position).getTranscod() == 2) {
                            showToastLong(getString(R.string.video_zzzm));
                        } else if (allDataInfoList.get(position).getTranscod() == 3) {
                            showToastLong(getString(R.string.video_ddzm));
                        }

                    } else {
                        showToastLong(getString(R.string.video_no_sel));
                    }
                } else {
                    if (!isSelect) {
                        cb.setVisibility(View.GONE);

                        if (null != allDataInfoList.get(position)) {
                            if (allDataInfoList.get(position).getTranscod() == 1) {
                                Intent intent = new Intent(getActivity().getApplicationContext(), VideoPlayerActivity.class);
                                intent.putExtra("video_file", position + "");
                                //getActivity().startActivityForResult(intent, 1000);
                                getActivity().startActivity(intent);
                            } else {
                                showToastLong(getString(R.string.video_ddzm));
                            }

                        }

                    } else {
                        cb.setVisibility(View.VISIBLE);
                        cb.setChecked(true);


                    }
                }
            }
        });
        mRlRight.setOnClickListener(this);
        mCbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //全选
                    if (EncodeAVIToMP4Service.getIsEncoding()) {
                        //正在转码
                        mCbSelectAll.setChecked(false);
                        oneDialog = new OneDialog(getActivity(), getString(R.string.video_no_all_sel), oneListener);
                        oneDialog.show();

                    } else {
                        //不在转码
                        state.clear();
                        mSelectList.clear();
                        for (int i = 0; i < allDataInfoList.size(); i++) {
                            mSelectList.add(allDataInfoList.get(i).getTitle());
                            state.put(i, true);

                        }
                        mAdapter.notifyDataSetChanged();
                        state.clear();
                        mSelectList.clear();
                        for (int i = 0; i < allDataInfoList.size(); i++) {
                            mSelectList.add(allDataInfoList.get(i).getTitle());
                            state.put(i, true);

                        }
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    //取消全选
                    state.clear();
                    mSelectList.clear();
                    mAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.video_rl_right:  //删除
                if (isSelect && mSelectList.size() != 0) {
                    //showTwoDialog();
                    showDele();
                } else {
                    showToastLong(getString(R.string.photo_no_sel));
                }
                break;
        }


    }

    private View.OnClickListener oneListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_update_one_rl:
                    oneDialog.dismiss();

            }
        }
    };

    private class FileAdapter extends BaseAdapter {


        public void updataView(int position, ListView listView) {
            int visibleFirstPosi = listView.getFirstVisiblePosition();
            int visibleLastPosi = listView.getLastVisiblePosition();
            if (position >= visibleFirstPosi && position <= visibleLastPosi) {
                View view = listView.getChildAt(position - visibleFirstPosi);
                ViewHolder holder = (ViewHolder) view.getTag();
                if (allDataInfoList.get(position).getTranscod() == 2) {
                    holder.ckSelect.setVisibility(View.GONE);
                    holder.tvZm.setVisibility(View.GONE);
                    holder.llZm.setVisibility(View.VISIBLE);
                    int pos = (int) (System.currentTimeMillis() - EncodeAVIToMP4Service.getCurrentEncodeTime()) / 1000;
                    if (pos >= 100) {
                        holder.tcProgross.startProgress(80);
                    } else {
                        holder.tcProgross.startProgress(pos);
                    }
                } else if (allDataInfoList.get(position).getTranscod() == 3) {
                    holder.ckSelect.setVisibility(View.GONE);
                    holder.tvZm.setVisibility(View.VISIBLE);
                    holder.llZm.setVisibility(View.GONE);
                    holder.tcProgross.stopProgress();
                } else {
                    if (isSelect) {
                        holder.ckSelect.setVisibility(View.VISIBLE);
                    }
                    holder.tvZm.setVisibility(View.GONE);
                    holder.llZm.setVisibility(View.GONE);
                    holder.tcProgross.stopProgress();
                }

            }
        }

        @Override
        public int getCount() {
            if (allDataInfoList == null) {
                return 0;
            }
            return allDataInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            if (allDataInfoList == null) {
                return null;
            }
            return allDataInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getActivity().getApplication(), R.layout.item_video, null);
                holder.tvData = (TextView) convertView
                        .findViewById(R.id.item_video_tv_data);
                holder.tvTime = (TextView) convertView
                        .findViewById(R.id.item_video_tv_time);
                holder.tvChang = (TextView) convertView.findViewById(R.id.item_video_tv_chang);
                holder.tvSize = (TextView) convertView
                        .findViewById(R.id.item_video_tv_size);
                holder.imPhoto = (ImageView) convertView.findViewById(R.id.item_video_im);
                holder.ckSelect = (CheckBox) convertView.findViewById(R.id.item_video_cb);

                holder.llZm = (LinearLayout) convertView.findViewById(R.id.item_video_ll_zz);
                holder.tcProgross = (TasksCompletedView) convertView.findViewById(R.id.item_video_proview);
                holder.tvZm = (TextView) convertView.findViewById(R.id.item_video_tv_zz);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.ckSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        if (!mSelectList.contains(allDataInfoList.get(position).getTitle())) {
                            mSelectList.add(allDataInfoList.get(position).getTitle());
                        }

                        state.put(position, isChecked);

                    } else {
                        //未选中 删除
                        if (mSelectList.contains(allDataInfoList.get(position).getTitle())) {
                            for (int i = 0; i < mSelectList.size(); i++) {
                                if (allDataInfoList.get(position).getTitle().equals(mSelectList.get(i))) {
                                    mSelectList.remove(i);
                                }
                            }
                        }

                        state.remove(position);
                    }
                }
            });
            if (isSelect) {
                holder.ckSelect.setVisibility(View.VISIBLE);
                holder.ckSelect.setChecked(state.get(position) == null ? false : true);
            } else {
                holder.ckSelect.setVisibility(View.GONE);
            }

            holder.tvTime.setText(allDataInfoList.get(position).getCreateDate().substring(allDataInfoList.get(position).getCreateDate().length() - 8));
            holder.tvSize.setText(getPrintSize(allDataInfoList.get(position).getSize()));
            syncResourceLoader.loadImage(holder, allDataInfoList.get(position), position, allDataInfoList);
            /*
            if (isExist(cutPath(allDataInfoList.get(position).getPath()))) {
                holder.imPhoto.setImageBitmap(mBitmapCache.getBitmap(cutPath(allDataInfoList.get(position).getPath())));
            } else {
                holder.imPhoto.setImageResource(R.mipmap.pic0);
            }
*/
            //第一条数据，肯定显示时间标题
            if (position == 0) {
                holder.tvData.setVisibility(View.VISIBLE);
                holder.tvData.setText(changeData(allDataInfoList.get(position).getCreateDate().substring(0, 8)));

            } else { // 不是第一条数据
                // 本条数据和上一条数据的时间戳相同，时间标题不显示
                if (allDataInfoList.get(position).getCreateDate().substring(0, 8)
                        .equals(allDataInfoList.get(position - 1).getCreateDate().substring(0, 8))) {
                    holder.tvData.setVisibility(View.GONE);

                } else {
                    //本条数据和上一条的数据的时间戳不同的时候，显示数据
                    holder.tvData.setVisibility(View.VISIBLE);
                    holder.tvData.setText(changeData(allDataInfoList.get(position).getCreateDate().substring(0, 8)));

                }
            }

            if (allDataInfoList.get(position).getTranscod() == 2) {
                //正在转码，此时没法选中
                holder.ckSelect.setVisibility(View.GONE);
                holder.tvZm.setVisibility(View.GONE);
                holder.llZm.setVisibility(View.VISIBLE);
                int pos = (int) (System.currentTimeMillis() - EncodeAVIToMP4Service.getCurrentEncodeTime()) / 1000;
                if (pos >= 100) {
                    holder.tcProgross.startProgress(80);
                } else {
                    holder.tcProgross.startProgress(pos);
                }

            } else if (allDataInfoList.get(position).getTranscod() == 3) {
                //等待转码
                holder.ckSelect.setVisibility(View.GONE);
                holder.tvZm.setVisibility(View.VISIBLE);
                holder.llZm.setVisibility(View.GONE);
                holder.tcProgross.stopProgress();
            } else {
                //转码完成
                holder.tvZm.setVisibility(View.GONE);
                holder.llZm.setVisibility(View.GONE);
                holder.tcProgross.stopProgress();
            }

            //holder.content.setText(list.get(position).getText());
            return convertView;
        }

    }

    private class ViewHolder {
        TextView tvData;
        TextView tvTime;
        TextView tvChang;
        TextView tvSize;
        ImageView imPhoto;
        CheckBox ckSelect;

        //转码相关
        LinearLayout llZm;
        TasksCompletedView tcProgross;
        TextView tvZm;

    }


    private String cutPath(String path) {
        int index = path.lastIndexOf(".");
        return path.substring(0, index) + ".JPG";
    }

    private boolean isExist(String path) {
        File file = new File(path);
        return file.exists();
    }


    public class SyncResourceLoader {

        private Object lock = new Object();

        private boolean mAllowLoad = true;

        private boolean firstLoad = true;

        private int mStartLoadLimit = 0;

        private int mStopLoadLimit = 0;

        final Handler handler = new Handler();

        private HashMap<String, SoftReference<Bitmap>> bitmapCache = new HashMap<String, SoftReference<Bitmap>>();

        public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
            if (startLoadLimit > stopLoadLimit) {
                return;
            }
            mStartLoadLimit = startLoadLimit;
            mStopLoadLimit = stopLoadLimit;
        }

        public void restore() {
            mAllowLoad = true;
            firstLoad = true;
        }

        public void lock() {
            mAllowLoad = false;
            firstLoad = false;
        }

        public void unlock() {
            mAllowLoad = true;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void loadImage(final ViewHolder holder, final FileInfo rm, Integer t, final List<FileInfo> routeInfoList) {
            final ViewHolder mImageUrl = holder;
            final FileInfo mRouteInfo = rm;
            final Integer mt = t;

            ThreadPoolManager.getLongPool().execute(new Runnable() {

                @Override
                public void run() {

                    if (!mAllowLoad) {
                        synchronized (lock) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    if (mAllowLoad) {
                        loadImage(holder, rm, routeInfoList);
                    }

                }

            });

        }

        private void loadImage(final ViewHolder holder, final FileInfo rm1, final List<FileInfo> routeInfoList) {

            final FileInfo rm = rm1;
            //final Bitmap dd = loadImageFromUrl(rm.getVideo_file());
            final Bitmap bitmap1 = mBitmapCache.getBitmap(rm.getPath());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (mAllowLoad) {

                        if (isExist(cutPath(rm.getPath()))) {
                            holder.imPhoto.setImageBitmap(mBitmapCache.getBitmap(cutPath(rm.getPath())));
                        } else {
                            holder.imPhoto.setImageResource(R.mipmap.pic0);
                        }

                    }
                }
            });
        }

    }

    /**
     * dialog弹出2
     */
    public static Bitmap ImageCrop(Bitmap bitmap) {

        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();

        int wh = w > h ? h : w;// 裁切后所取的正方形区域边长

        int retX = w > h ? (w - h) / 2 : 0;//基于原图，取正方形左上角x坐标
        int retY = w > h ? 0 : (h - w) / 2;

        //下面这句是关键
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, null, false);
    }

    private void showDele() {
        twoDialog = new TwoDialog(getActivity(), getString(R.string.dialog_tip), getString(R.string.photo_sel1) + " " + mSelectList.size() + " " + getString(R.string.video_sel2) + "?", deleListener);
        twoDialog.show();
    }

    private View.OnClickListener deleListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    handler1.sendEmptyMessageDelayed(1112, 10);

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private void showTwoDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(getActivity(), R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);
        tvInfo.setText("确认删除选中的" + mSelectList.size() + "个视频");
        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dialog.dismiss();
                handler1.sendEmptyMessageDelayed(1112, 10);

                /*
                for (int i = 0; i < mSelectList.size(); i++) {
                    deleteFile((String) mSelectList.get(i));
                    deleteFile(((String) mSelectList.get(i)).substring(0, ((String) mSelectList.get(i)).lastIndexOf(".")) + ".JPG");
                }
                */

            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);
    }

    private void deleFile() {

        for (int i = 0; i < mSelectList.size(); i++) {
            deleteFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + ((String) mSelectList.get(i)).substring(0, ((String) mSelectList.get(i)).lastIndexOf(".")) + ".mp4");
            deleteFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/video/" + mSelectList.get(i));
            deleteFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/video/" + ((String) mSelectList.get(i)).substring(0, ((String) mSelectList.get(i)).lastIndexOf(".")) + ".JPG");
        }
        //initData();
        for (int i = 0; i < mSelectList.size(); i++) {
            for (int j = 0; j < allDataInfoList.size(); j++) {

                if (mSelectList.get(i).equals(allDataInfoList.get(j).getTitle())) {
                    allDataInfoList.remove(j);
                }
            }
        }
        mSelectList.clear();
        state.clear();
    }

    private Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1111:
                    pd.dismiss();
                    initData();
                    closeSelect();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 1112:
                    pd = ProgressDialog.show(getActivity(), getString(R.string.dialog_tip), getString(R.string.load_wait));
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            deleFile();// 耗时的方法
                            handler1.sendEmptyMessage(1111);// 执行耗时的方法之后发送消给handler
                        }
                    }).start();
                    break;
            }
        }
    };

    public static String getPrintSize(long size) {

        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }

        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            size = size * 100;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB";
        } else {

            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
        }
    }

}
